package com.sitech.ibnms.c3p.quartz;

import com.sitech.ibnms.c3p.mappers.C3pManualTaskMapper;
import com.sitech.ibnms.c3p.task.C3pServerLogTaskService;
import com.sitech.ibnms.c3p.task.C3pTaskFlowServiceExtends;
import com.sitech.ismp.workflow.dao.TaskDAO;
import com.sitech.ismp.workflow.domain.Task;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.ignite.Ignite;
import org.apache.ignite.lang.IgniteRunnable;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

import static com.sitech.ibnms.c3p.Application.getBean;

/**
 * 检查超时任务
 * Created by leo on 15/6/25.
 */
public class C3pNodeWatchdogJob implements Job {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private Ignite ignite;
//检查环节超时 ，
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        ignite.compute().run(new IgniteRunnable() {
            @Override
            public void run() {
                try {
                    List<Task> tasks = getBean(C3pManualTaskMapper.class).queryTimeoutUnManualTask();
                    for (Task task : tasks) {
                        try {
                            getBean(C3pServerLogTaskService.class).writeTaskNodeLog(task, "环节【${nodeName}】执行失败（超时未结束）");
                            getBean(C3pTaskFlowServiceExtends.class).failPolicy(task, new RuntimeException("超时未结束"));
                        } catch (Exception e) {
                            logger.error("Process timeout task node failed: " + ToStringBuilder.reflectionToString(task), e);
                        } finally {
                            task.setDealType("-1");
                            getBean(TaskDAO.class).updatTask(task);
                        }
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        });
    }
}
